#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <cerrno>
#include <cstring>
#include <fcntl.h>

// 对指定的文件描述符设置为非阻塞
bool SetNonBlock(int fd)
{
    int fl = fcntl(fd, F_GETFL); // 在底层获取当前fd对应的文件读写标志位
    if (fl < 0)
    {
        std::cout << "fcntl error" << std::endl;
        return false;
    }
    fcntl(fd, F_SETFL, fl | O_NONBLOCK);
}

int main()
{
    SetNonBlock(0); // 只要设置一次，0号文件描述符就是非阻塞的了
    char buffer[1024];
    while (true)
    {
        sleep(1);
        errno = 0;
        ssize_t s = read(0, buffer, sizeof(buffer) - 1);
        if (s > 0)
        {
            buffer[s - 1] = 0;
            //std::cout << "echo# " << buffer << std::endl;
            std::cout << "echo# " << buffer << ", erron: " << errno << ", errorstring: " << strerror(errno) << std::endl;
        }
        else
        {
            // std::cout << "read \"error\"" << std::endl;
            // std::cout << "erron: " << errno << ", errorstring: " << strerror(errno) << std::endl;
            if (errno == EWOULDBLOCK || errno == EAGAIN)
            {
                std::cout << "当前0号fd数据没有就绪, 请再试一次" << std::endl;
                continue;
            }
            else if (errno == EINTR)
            {
                std::cout << "当前IO可能被信号中断, 请再试一次" << std::endl;
                continue;
            }
            else 
            {
                // 差错处理
            }
        }

    }
    return 0;
}